package com.geek.factory.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.entity.Material;
import com.geek.factory.entity.MaterialSupplier;
import com.geek.factory.entity.Supplier;
import com.geek.factory.result.Result;
import com.geek.factory.service.IMaterialService;
import com.geek.factory.service.MaterialSupplierService;
import com.geek.factory.service.SupplierService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-06-19
 */
@RestController
@RequestMapping("/supplier")
@Api(tags = "后台系统的 - 供应商模块")
@Slf4j
public class SupplierController {
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private MaterialSupplierService materialSupplierService;
    @Autowired
    private IMaterialService materialService;

    @ApiOperation("通过ID查询用户信息")
    @GetMapping("{supplierId}")
    public Result findUserById(@ApiParam("供应商ID") @PathVariable("supplierId") Integer supplierId) {
        Supplier supplier = supplierService.getById(supplierId);
        log.info("user: {}", supplier);
        if (supplier != null) {
            return new Result(SuccessConstant.SUCCESS, "ok", supplier);
        }
        return new Result(SuccessConstant.FAIL, "不ok");
    }

    // 新增供应商
    @ApiOperation("新增供应商")
    @PostMapping
    public Result addSupplier(@RequestBody Supplier supplier) {
        boolean isSuccess = supplierService.save(supplier);
        log.info("新增供应商: {}, 结果: {}", supplier, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "新增成功", supplier);
        }
        return new Result(SuccessConstant.FAIL, "新增失败");
    }

    // 根据ID删除供应商
    @ApiOperation("根据ID删除供应商")
    @DeleteMapping("{supplierId}")
    public Result deleteSupplier(@ApiParam("供应商ID") @PathVariable("supplierId") Integer supplierId) {
        boolean isSuccess = supplierService.removeById(supplierId);
        log.info("删除供应商ID: {}, 结果: {}", supplierId, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "删除成功");
        }
        return new Result(SuccessConstant.FAIL, "删除失败");
    }

    // 修改供应商信息
    @ApiOperation("修改供应商信息")
    @PutMapping
    public Result updateSupplier(@RequestBody Supplier supplier) {
        boolean isSuccess = supplierService.updateById(supplier);
        log.info("修改供应商: {}, 结果: {}", supplier, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "修改成功", supplier);
        }
        return new Result(SuccessConstant.FAIL, "修改失败");
    }

    @GetMapping("/page")
    public Result getSupplierPage(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) String supplierName,
            @RequestParam(required = false) String contactPerson
    ) {
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(supplierName)) {
            wrapper.like("supplier_name", supplierName);
        }
        if (StringUtils.isNotBlank(contactPerson)) {
            wrapper.like("contact_person", contactPerson);
        }
        Page<Supplier> page = supplierService.page(new Page<>(pageNum, pageSize), wrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("records", page.getRecords());
        data.put("total", page.getTotal());
        return new Result(SuccessConstant.SUCCESS, "查询成功", data);
    }


    @GetMapping("/{supplierId}/with-materials")
    public Result getSupplierWithMaterials(@PathVariable("supplierId") Integer supplierId) {
        Supplier supplier = supplierService.getById(supplierId);
        if (supplier == null) {
            return new Result(SuccessConstant.FAIL, "供应商不存在");
        }
        List<MaterialSupplier> materials = materialSupplierService.getBySupplierId(supplierId);
        for (MaterialSupplier ms : materials) {
            Material material = materialService.getById(ms.getMaterialId());
            if (material != null) {
                ms.setMaterialName(material.getMaterialName());
                ms.setMaterialCode(material.getMaterialCode());
            }
        }
        supplier.setMaterials(materials);
        return new Result(SuccessConstant.SUCCESS, "查询成功", supplier);
    }
    @ApiOperation("获取所有供应商列表")
    @GetMapping("/list")
    public Result getAllSuppliers() {
        try {
            List<Supplier> suppliers = supplierService.list();
            return new Result(SuccessConstant.SUCCESS, "查询成功", suppliers);
        } catch (Exception e) {
            log.error("获取供应商列表失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }

}
